/**
 * @param {number[]} customers
 * @param {number[]} grumpy
 * @param {number} minutes
 * @return {number}
 */
var maxSatisfied = function (customers, grumpy, minutes) {
	const n = customers.length
	let total = 0
	for (let i = 0; i < n; i++) {
		if (!grumpy[i]) {
			total += customers[i]
		}
	}
	let l = 0,
		r = 0
	while (r < minutes) {
		if (grumpy[r]) {
			total += customers[r]
		}
		r++
	}
	let max = total
	r-- // 回到右边界
	while (r < n) {
		// l 离开，原本不满意的，回到以前
		if (grumpy[l]) {
			total -= customers[l]
		}
		l++
		r++
		if (grumpy[r]) {
			total += customers[r]
		}
		max = Math.max(max, total)
	}
	return max
}
var maxSatisfied = (customers, grumpy, minutes) => {
	const n = customers.length
	let total = 0
	for (let i = 0; i < n; i++) {
		if (!grumpy[i]) {
			total += customers[i]
		}
	}
	let max = total
	for (let i = 0; i < n; i++) {
		// 第一个滑动窗口中不满意的 ++
		if (i < minutes) {
			grumpy[i] && (total += customers[i])
		} else {
			// 滑动窗口右移 (i - m, i] 左-右+
			if (grumpy[i - minutes]) {
				total -= customers[i - minutes]
			}
			if (grumpy[i]) {
				total += customers[i]
			}
		}
		max = Math.max(max, total)
	}
	return max
}
// 一次遍历
var maxSatisfied = (customers, grumpy, minutes) => {
	let [n, t, m] = [0, 0, 0]
	for (let i = 0; i < customers.length; i++) {
		!grumpy[i] && (n += customers[i])
		if (i < minutes) {
			grumpy[i] && (t += customers[i])
		} else {
			if (grumpy[i - minutes]) {
				t -= customers[i - minutes]
			}
			if (grumpy[i]) {
				t += customers[i]
			}
		}
		m = Math.max(m, t)
	}
	return n + m
}
const res = maxSatisfied([1, 0, 1, 2, 1, 1, 7, 5], [0, 1, 0, 1, 0, 1, 0, 1], 3)
console.log(res)
